package com.taobao.action;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.taobao.factory.TBFactory;

public abstract class CommonAction {

    public static Object lock = new Object();

    private Boolean stop = false;
    
    private Map<Object, Object> paras = new HashMap<Object, Object>();

    public CommonAction() {
        List<Object> objectList = TBFactory.initAttributeObject(this.getClass());
        Field[] fields = this.getClass().getDeclaredFields();
        int no = 0;
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            String fieldName = field.getName();
            int flag = fieldName.indexOf("Server");
            if (flag != -1 && (flag + "Server".length() == fieldName.length() || flag + "ServerSingle".length() == fieldName.length())) {
                try {
                    field.set(this, objectList.get(no));
                    no++;
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void lockAction() {
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void unLockAction() {
        synchronized (lock) {
            lock.notifyAll();
        }
    }

    public void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public CommonAction getThis() {
        return this;
    }

    public String getActionName() {
        return toString();
    }

    public void stop() {
        synchronized (stop) {
            this.stop = true;
        }
    }

    public boolean isStop() {
        synchronized (stop) {
            return this.stop;
        }
    }
    
    public Object getData(Object key) {
        return paras.get(key);
    }

    public void setData(Object key, Object value) {
        paras.put(key, value);
    }
    
    public abstract void doAction(Object uiObject);

}
